package com.application.lucky.activity;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

import com.application.lucky.R;
import com.application.lucky.bean.eventbean.ForceUpgradeEvent;
import com.application.lucky.bean.eventbean.GroupUnreadEvent;
import com.application.lucky.bean.eventbean.HomePointEvent;
import com.application.lucky.fragment.main.FragmentActivity;
import com.application.lucky.fragment.main.FragmentContacts;
import com.application.lucky.fragment.main.FragmentGroup;
import com.application.lucky.fragment.main.FragmentMe;
import com.application.lucky.fragment.main.FragmentP2;
import com.application.lucky.fragment.main.LoginEvent;
import com.application.lucky.manager.SocketListenerManager;
import com.application.lucky.widget.bottombar.BottomBarItem;
import com.application.lucky.widget.bottombar.BottomBarLayout;
import com.application.lucky.widget.dialog.SignleButtonDialog;
import com.application.mylibrary.base.BaseActivity;
import com.qunar.im.core.manager.IMDatabaseManager;
import com.qunar.im.protobuf.common.CurrentPreference;
import com.qunar.im.utils.AppFrontBackHelper;
import com.qunar.im.utils.ConnectionUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends BaseActivity implements
        BottomBarLayout.OnItemSelectedListener, EasyPermissions.PermissionCallbacks {
    private HashMap<Integer, Fragment> fragments = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    BottomBarLayout mMainBottomTab;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    private void initView() {
        initActivityLifeCycle();
        mMainBottomTab = findViewById(R.id.main_bottom_tab);
        mMainBottomTab.setOnItemSelectedListener(this);
        setFragmentPosition(0);
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 已获取权限
            // ...

        } else {
            // 没有权限，现在去获取
            // ...
            EasyPermissions.requestPermissions(this, "申请内存权限",
                    1, perms);
        }
//        initActivityLifeCycle();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 一些权限被授予
        Toast.makeText(this, "允许", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // 一些权限被禁止
        Toast.makeText(this, "禁止", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isLogin)
            mMainBottomTab.setUnread(0, IMDatabaseManager.getInstance().SelectP2UnReadCount());
        mMainBottomTab.setUnread(2, IMDatabaseManager.getInstance().SelectGroupUnReadCount());


    }

    private boolean isLogin = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void islogin(LoginEvent loginEvent) {
        isLogin = true;
        mMainBottomTab.setUnread(0, IMDatabaseManager.getInstance().SelectP2UnReadCount());
    }

    private int retry = 0;

    private void initActivityLifeCycle() {
        AppFrontBackHelper helper = new AppFrontBackHelper();
        helper.register(getApplication(), new AppFrontBackHelper.OnAppStatusListener() {
            @Override
            public void onFront() {
                //应用切到前台处理
                CurrentPreference.getInstance().setBack(false);

                if (!ConnectionUtil.getInstance().isLoginStatus()) {
                    ConnectionUtil.getInstance().reConnectionForce();
                }

            }

            @Override
            public void onBack() {
                //应用切到后台处理
                CurrentPreference.getInstance().setBack(true);
            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // 将返回结果转给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private Fragment currentFragment;

    private void setFragmentPosition(int i) {
        Fragment next = fragments.get(i);
        if (next == null) {
            switch (i) {
                case 0:
                    // 第一个消息的fragment
                    next = new FragmentP2();
                    break;
                case 1:
                    // 第二个通讯的fragment
                    next = new FragmentContacts();
                    break;
                case 2:
                    // 第三个群组的fragment
                    next = new FragmentGroup();
                    break;
                case 3:
                    // 第三个活动的fragment
                    next = new FragmentActivity();
                    break;
                case 4:
                    // 第四个Me的fragment
                    next = new FragmentMe();
                    break;
            }
            fragments.put(i, next);
        }
        if (currentFragment == next) {
            return;
        }
        FragmentManager manager = getSupportFragmentManager();
        if (manager != null) {
            FragmentTransaction transaction = manager.beginTransaction();
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            if (next != null) {
                if (!next.isAdded()) {
                    try {
                        transaction.add(R.id.fragment, next, i + "");
                    } catch (IllegalStateException e) {

                    }
                } else {
                    transaction.show(next);
                }
                currentFragment = next;
                transaction.commitAllowingStateLoss();
            }
        }

    }

    @Override
    public void beforeInit() {

    }


    @Override
    public void onItemSelected(BottomBarItem bottomBarItem, int previousPosition, int currentPosition) {
        setFragmentPosition(currentPosition);
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Subscribe
    public void receiverMessage(HomePointEvent e) {
        switch (e.tab) {
            case HomePointEvent.TAB_message:
                if (mMainBottomTab != null) {
                    mMainBottomTab.setUnread(e.tab, IMDatabaseManager.getInstance().SelectP2UnReadCount() + SocketListenerManager.getInstance().getUnreadCOunt());
                }
                break;

            case HomePointEvent.TAB_contact:
                if (mMainBottomTab != null) {
                    if (e.isShow) {
                        mMainBottomTab.showNotify(e.tab);
                    } else {
                        mMainBottomTab.hideNotify(e.tab);
                    }

                }
                break;
            case HomePointEvent.TAB3_group:
                if (mMainBottomTab != null) {
                    mMainBottomTab.setUnread(e.tab, IMDatabaseManager.getInstance().SelectGroupUnReadCount());
                }
                break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUnReadEvent(GroupUnreadEvent event) {
        mMainBottomTab.setUnread(0, IMDatabaseManager.getInstance().SelectP2UnReadCount() + SocketListenerManager.getInstance().getUnreadCOunt());
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventUpgrade(ForceUpgradeEvent event) {
        if (logoutDialog != null && logoutDialog.isShowing()) {
            return;
        }
        logoutDialog = null;
        showLogoutDialog();
    }

    private SignleButtonDialog logoutDialog;

    private void showLogoutDialog() {
        logoutDialog = new SignleButtonDialog.Build(MainActivity.this)
                .disMiss(true)
                .setMessage("当前版本过低，更新后才能使用？")
                .setRightButton("更新", new SignleButtonDialog.BaseDialogClickListener() {
                    @Override
                    public void click() {
                        logoutDialog.dismiss();
                    }
                }).create();
        logoutDialog.setCanceledOnTouchOutside(false);
        logoutDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (logoutDialog != null && logoutDialog.isShowing()) {
            logoutDialog.dismiss();
        }
    }
}
